package stages;

import java.util.ArrayList;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;

import framework.Bird;
import framework.Stage;
import framework.Util;

public class Mountains extends Stage {
	
	private final static int MIN_SPAWN_FREQUENCY = 100;
	
	private final static int MAX_SPAWN_FREQUENCY = 4000;
	
	protected int spawn;
	
	protected int lastSpawn;
	
	protected int currentTime;
	
	protected ArrayList<Bird> birds;
	
	public Mountains() {
		super();
		lastSpawn = 0;
		currentTime = 0;
		birds = new ArrayList<>();
		spawn = Util.randomize(MIN_SPAWN_FREQUENCY, MAX_SPAWN_FREQUENCY);
	}

	@Override
	public void update(GameContainer gc, int delta) {
		super.update(gc, delta);
		currentTime += delta;
		if (currentTime > lastSpawn + spawn) {
			lastSpawn += spawn;
			Bird b = new Bird();
			birds.add(b);
			b.setScale(getScale());
			int y = Util.randomize(gc.getHeight() / 20, gc.getHeight() / 3);
			int left = Util.randomize(0, 1);
			b.setY(y);
			if (left == 1) {
				b.setX(gc.getWidth());
				b.setXspeed(-b.getXspeed());
			}
			spawn = Util.randomize(MIN_SPAWN_FREQUENCY, MAX_SPAWN_FREQUENCY);
		} 
		
		for (int i=0; i < birds.size(); i++) {
			Bird b = birds.get(i);
			b.update(gc, delta);
			if (b.getX() > gc.getWidth() || b.getX() + b.getWidth() < 0) {
				birds.remove(i);
			}
		}
	}

	@Override
	public void draw(Graphics g) {
		super.draw(g);
		for (Bird bird : birds) {
			bird.draw(g);
		}
	}	
}

